import type { AxiosResponse } from "axios"
import dayjs from "dayjs"

type ITreeOptions<T extends Record<string, unknown>, K = keyof T> = {
  id: K,
  parentId?: K,
  rootId?: number
}

interface ITree {
  [key: string]: unknown
  children?: ITree[]
}

export function arr2tree<T extends ITree>(arr: T[], options: ITreeOptions<T>) {
  const { id, parentId = 'pid', rootId = 0 } = options
  const arrMap = arr.reduce((pre, cur) => {
    pre[cur[id] as string] = cur
    return pre
  }, {} as Record<string, T>)
  const root: T[] = []
  arr.forEach(item => {
    if (item[parentId as string] == rootId) {
      root.push(item);
    } else {
      const parent = arrMap[item[parentId] as string]
      if (!!parent) {
        if (!parent.children) {
          parent.children = []
        }
        parent.children.push(item)
      }
    }
  })
  return root
}

/**
 * 获取uuid
 */
export function getUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}
/**
 * 文件下载
 * @param {Object} res 接口返回数据
 * @param {String} fileName 文件名
 */
export async function download(res: AxiosResponse, fileName?: string) {
  if (res.data.type === 'application/json') {
    const enc = new TextDecoder('utf-8');
    const buffer = await res.data.arrayBuffer()
    const data = JSON.parse(enc.decode(buffer)) || {};
    AntNotification.error({
      message: '下载错误',
      description: data.msg as string
    })
    return false
  }
  const content = res.data
  const name = res.headers['content-disposition'] && decodeURI(res.headers['content-disposition'].split('filename=')[1])
  const blob = new Blob([content], { type: res.headers['content-type'] || 'application/vnd.ms-excel;charset=utf-8' }) // 创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
  const url = window.URL.createObjectURL(blob)// URL.createObjectURL(object)表示生成一个File对象或Blob对象
  const dom = document.createElement('a')// 设置一个隐藏的a标签，href为输出流，设置download
  dom.style.display = 'none'
  dom.href = url
  dom.setAttribute('download', name || fileName || dayjs().format('YYYYMMDD') + '.xlsx')// 指示浏览器下载url,而不是导航到它；因此将提示用户将其保存为本地文件
  document.body.appendChild(dom)
  dom.click()
  return true
}

export function setDomain(url: string) {
  url = url ? url.toString() : '';
  // 正则替换存在的转义符
  url = url.replace(/\\/g, '');
  url = window.location.protocol === 'https:' ? url.replace('http://', 'https://') : url;
  if (url.startsWith('src="')) {
    url = url.replaceAll('src="', '');
  }
  if (url.startsWith('//img') && window.location.protocol === 'https:') {
    url = url.replace('//img', 'https://img');
  }
  return url;
}

// 过滤富文本中的 img 相对路径访问
export function replaceImgSrcHttps(content: string) {
  return content.replaceAll('src="//', 'src="https://');
}